#include "soc_iwdg.h"
#include "main.h"

#define WDG_PERIOD_MAX 8000

SOF_IWDG::SOF_IWDG(void *handle)
{
    m_devId = 0;
    m_socHandle = handle;
}

SOF_IWDG::~SOF_IWDG()
{
}

/// @brief Tout=((4×2^PR) ×RLR)/LSI
/// @param ms 
void SOF_IWDG::SetPeriod(int period)
{
    m_period = period;
    if(m_period > WDG_PERIOD_MAX)
    {
        m_period = WDG_PERIOD_MAX;
    }
}

void SOF_IWDG::Start()
{
    if(m_period == 0)
        return;
    
    auto h = GetThisHandleAs<IWDG_HandleTypeDef>();    
    if(h == nullptr)
        return;

    //32K / 64
    int load = m_period / 2;
    if(load > 4096)
        load = 4096;

    h->Instance = IWDG;
    h->Init.Prescaler = IWDG_PRESCALER_64; 
    h->Init.Window = load - 1;
    h->Init.Reload = load -1;
    if (HAL_IWDG_Init(h) != HAL_OK)
    {
        Error_Handler();
    }
}

void SOF_IWDG::Stop()
{
}

void SOF_IWDG::Feed()
{
    auto h = GetThisHandleAs<IWDG_HandleTypeDef>();    
    if(h == nullptr)
        return;

    __HAL_IWDG_RELOAD_COUNTER(h);
}
